package com.dimeng;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.ScrollingMovementMethod;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dimeng.entity.MettlePhotoAlumb;
import com.dimeng.listener.MulitPointTouchListener;
import com.dimeng.utils.AppCache;
import com.dimeng.utils.AsyncImageLoader;
import com.dimeng.utils.AsyncImageLoader.ImageCallback;
import com.dimeng.utils.CommonUtil;
import com.dimeng.utils.Constant;
import com.dimeng.utils.FileUtilsByCCN;
import com.dimeng.utils.LoadDataThread;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * @author write by ccn<br>
 *         <b>helloandroid100@gmail.com</b>
 * @version 0.1;2012-7-4 上午11:51:06<br>
 *          descrition:浏览相册的图片
 */
public class BrowseMettlePhotoActivity extends SuperActivity implements OnGestureListener {
	private static final long serialVersionUID = -9020237689071500957L;
	private final static String ALBUM_PATH = Constant.SDCARD_PATH + "/taojindi/alumb/";
	private List<MettlePhotoAlumb> albumList;
	private List<MettlePhotoAlumb> photoList;
	private String albumId;
	private String url;
	private String imageUrl;
	private int alumbPosition;
	private TextView positionTextView;
	private ImageView imageView;
	private Drawable drawble;
	private RelativeLayout toolsLayout;
	private TextView descriptionTV;
	private ImageButton saveToSDcardButton;
	private ImageButton showDescButton;
	private boolean clickShowDescFlag;// 显示图片描述
	private boolean imageClickFlag;// 点击图片
	private Thread loadDataThread;
	private Thread savePhotoToSdCardThread;
	private Gson gson = new Gson();
	private Context context;
	private GestureDetector mGestureDetector;
	private static final int FLING_MIN_DISTANCE = 50;
	private static final int FLING_MIN_VELOCITY = 0;
	private Map<String, List<MettlePhotoAlumb>> albumIdPhotosMap = new HashMap<String, List<MettlePhotoAlumb>>();
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case -1:
				String path = (String) msg.obj;
				Toast.makeText(BrowseMettlePhotoActivity.this,
						"成功保存图片到" + path + "目录", Toast.LENGTH_SHORT).show();
				break;
			case -2:
				Toast.makeText(BrowseMettlePhotoActivity.this, "保存图片到sd卡失败",
						Toast.LENGTH_SHORT).show();
				break;
			case 0:
				Toast.makeText(BrowseMettlePhotoActivity.this, "已加载所有数据",
						Toast.LENGTH_SHORT).show();
				break;
			case 1:
				String json = (String) msg.obj;
				List<MettlePhotoAlumb> loadList = gson.fromJson(json,
						new TypeToken<List<MettlePhotoAlumb>>() {
						}.getType());
				albumIdPhotosMap.put(albumId, loadList);
				photoList = photoList == null ? new ArrayList<MettlePhotoAlumb>()
						: photoList;
				photoList.clear();
				photoList.addAll(loadList);
				setTextViewImage();
				break;
			case 2:
				Toast.makeText(BrowseMettlePhotoActivity.this,
						Constant.NET_ERROR, Toast.LENGTH_LONG).show();
				break;
			default:
				break;
			}
		};
	};

	@SuppressWarnings("unchecked")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = this;
		setContentView(R.layout.browse_mettle_photo);
		positionTextView = (TextView) findViewById(R.id.positionTextViewId);
		imageView = (ImageView) findViewById(R.id.imageViewId);
		toolsLayout = (RelativeLayout) findViewById(R.id.toolsLayoutId);
		descriptionTV = (TextView) findViewById(R.id.description);
		descriptionTV.setMovementMethod(ScrollingMovementMethod.getInstance());
		saveToSDcardButton = (ImageButton) findViewById(R.id.saveToSDcardId);
		showDescButton = (ImageButton) findViewById(R.id.showDescId);
		CommonUtil.setButtonFocusChanged(saveToSDcardButton);
		CommonUtil.setButtonFocusChanged(showDescButton);

		Intent intent = getIntent();
		Bundle bd = intent.getExtras();
		albumId = bd.getString("ablumId");
		alumbPosition = bd.getInt("alumbPosition", 0);
		int pp = bd.getInt("photoPosition", -1);
		if(AppCache.photoPosition < pp)
			AppCache.photoPosition = pp;
		photoList = (List<MettlePhotoAlumb>) bd.get("photoList");
		albumList = (List<MettlePhotoAlumb>) bd.get("alumbList");
		if (null != photoList && photoList.size() > 0) {
			setTextViewImage();
		}
		imageView.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (!imageClickFlag) {
					positionTextView.setVisibility(View.VISIBLE);
					toolsLayout.setVisibility(View.VISIBLE);
					imageClickFlag = true;
				} else {
					positionTextView.setVisibility(View.GONE);
					toolsLayout.setVisibility(View.GONE);
					imageClickFlag = false;
				}
			}
		});
		
		imageView.setOnLongClickListener(new OnLongClickListener() {
			@Override
			public boolean onLongClick(View v) {
				
				return false;
			}
		});

		mGestureDetector = new GestureDetector(this);
		imageView.setOnTouchListener(new MulitPointTouchListener(mGestureDetector));
		imageView.setLongClickable(true);

		saveToSDcardButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				startSavePhotoToSdCardThread();
			}
		});
		showDescButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (!clickShowDescFlag) {
					descriptionTV.setVisibility(View.GONE);
					showDescButton.setBackgroundDrawable(getResources()
							.getDrawable(R.drawable.up));
					clickShowDescFlag = true;
				} else {
					descriptionTV.setVisibility(View.VISIBLE);
					showDescButton.setBackgroundDrawable(getResources()
							.getDrawable(R.drawable.down));
					clickShowDescFlag = false;
				}
			}
		});
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(KeyEvent.KEYCODE_BACK == keyCode){
			AppCache.photoPosition = 0;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void showPic(int position) {
		if (null != photoList && position >= photoList.size()) {
			if (alumbPosition + 1 < albumList.size()) {
				Toast.makeText(BrowseMettlePhotoActivity.this, "正在载入下一集相册",
						Toast.LENGTH_SHORT).show();
				alumbPosition += 1;
				albumId = albumList.get(alumbPosition).getAblumId() + "";
				url = Constant.HOST_URL + "mettlePhotos.do?ablumId="+ albumId.trim();
				photoList = albumIdPhotosMap.get(albumId);
				AppCache.photoPosition = 0;
				if (null == photoList || 0 == photoList.size()) {
					startLoadDataThread();
				} else {
					setTextViewImage();
				}
			} else {
				Toast.makeText(BrowseMettlePhotoActivity.this, "已经是最后一集相册了",
						Toast.LENGTH_SHORT).show();
			}
		} else if (position >= 0) {
			AppCache.photoPosition = position;
			setTextViewImage();
		} else {
			AppCache.photoPosition = 0;
			if (alumbPosition - 1 >= 0) {
				alumbPosition = alumbPosition - 1;
				albumId = albumList.get(alumbPosition).getAblumId() + "";
				url = Constant.HOST_URL + "mettlePhotos.do?ablumId="+ albumId.trim();
				photoList = albumIdPhotosMap.get(albumId);
				Toast.makeText(BrowseMettlePhotoActivity.this, "正在载入上一集相册",
						Toast.LENGTH_SHORT).show();
				if (null == photoList || 0 == photoList.size()) {
					startLoadDataThread();
				} else {
					setTextViewImage();
				}
			} else {
				Toast.makeText(BrowseMettlePhotoActivity.this, "已经是第一集相册了",
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	private void setTextViewImage() {
		if(null == photoList)
			return;
		MettlePhotoAlumb mpa = photoList.get(AppCache.photoPosition);
		if(null == mpa)
			return;
		String description = mpa.getPhotoDesc();
		if (null != description && !"".equals(description.trim())) {
			descriptionTV.setText(description);
		} else {
			descriptionTV.setVisibility(View.GONE);
		}
		positionTextView.setText((AppCache.photoPosition + 1) + "/" + photoList.size());
		imageUrl = photoList.get(AppCache.photoPosition).getImageUrl();
		imageView.setScaleType(ScaleType.FIT_CENTER);
		if(null != imageUrl && !"".equals(imageUrl)){
			drawble = AsyncImageLoader.getInstance().loadDrawable(imageUrl, new ImageCallback(){
				public void imageLoaded(Drawable imageDrawable, String imageUrl) {
					imageView.setImageDrawable(imageDrawable);
					drawble = imageDrawable;
				}});
			imageView.setImageDrawable(drawble);
		}
	}

	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		if (e1.getX() - e2.getX() > FLING_MIN_DISTANCE
				&& Math.abs(velocityX) > FLING_MIN_VELOCITY) {// Fling left
			int position = AppCache.photoPosition + 1;
			showPic(position);
		} else if (e2.getX() - e1.getX() > FLING_MIN_DISTANCE
				&& Math.abs(velocityX) > FLING_MIN_VELOCITY) {// Fling right
			int position = AppCache.photoPosition - 1;
			showPic(position);
		}
		return true;
	}
	@Override
	public boolean onDown(MotionEvent e) {
		return false;
	}
	@Override
	public void onLongPress(MotionEvent e) {
		if(null != drawble){
			File file = new File(Constant.IMG_CACHE_PATH+CommonUtil.getMD5String(imageUrl));
		    Uri _captureUri = Uri.fromFile(file);
			CommonUtil.startToCropImage(this,_captureUri);
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(Constant.CROP_REQUEST_CODE == requestCode && null != data){
			Bundle extras = data.getExtras();
			Bitmap photo = extras.getParcelable("data");
			try {
				this.setWallpaper(photo);
				Toast.makeText(context, "成功设置此图为壁纸.", Toast.LENGTH_SHORT).show();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		return false;
	}
	@Override
	public void onShowPress(MotionEvent e) {
	}
	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		return false;
	}

	/** 开启下载数据的线程 **/
	public void startLoadDataThread() {
		if (null == loadDataThread || !loadDataThread.isAlive()) {
			loadDataThread = new LoadDataThread(url, Constant.CHARSET_GBK,handler,true);
			loadDataThread.start();
		}
	}

	/** 保存图片到SD卡中 **/
	public void startSavePhotoToSdCardThread() {
		if (null == savePhotoToSdCardThread
				|| !savePhotoToSdCardThread.isAlive()) {
			loadDataThread = new Thread() {
				@Override
				public void run() {
					String lastName = imageUrl.substring(imageUrl
							.lastIndexOf("."));
					String path = ALBUM_PATH + albumId.replaceAll("-", "").trim();
					try {
						FileUtilsByCCN.createDir(path);
					} catch (IOException e) {
						e.printStackTrace();
					}
					Message msg = new Message();
					String fileName = path + "/" + AppCache.photoPosition + lastName;
					if(null != drawble){
						Bitmap bitmap = ((BitmapDrawable)drawble).getBitmap();
						CommonUtil.saveBitmapToSdcard(fileName,bitmap);
						msg.what = -1;
						msg.obj = path;
					}
					handler.sendMessage(msg);
				}
			};
			loadDataThread.start();
		}
	}
}
